package bsf.baseservice.distributedcache.storage.aliyunmemcached;

import bsf.baseservice.distributedcache.systemruntime.DistributedCacheConnectException;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;

import java.io.IOException;

/** 
 客户端连接池

*/
public class AliyunMemcachedClientPoolProvider
{
	private static java.util.HashMap<AliyunMemcachedCacheConfig, MemcachedClient> pools = new java.util.HashMap<AliyunMemcachedCacheConfig, MemcachedClient>();
	private static Object lockpool = new Object();

	public MemcachedClient getPool(AliyunMemcachedCacheConfig config)
	{
		if (pools.containsKey(config))
		{
			return pools.get(config);
		}
		synchronized (lockpool)
		{
			if (pools.containsKey(config))
			{
				return pools.get(config);
			}
			AuthDescriptor ad = new AuthDescriptor(new String[]{"PLAIN"}, new PlainCallbackHandler(config.UserName, config.Password));
			MemcachedClient pool = null;
			try {
				pool= new MemcachedClient(new ConnectionFactoryBuilder().setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
						.setAuthDescriptor(ad)
						.build(),
						AddrUtil.getAddresses(config.NetworkAddress + ":" + config.Port));
			}
			catch (IOException e)
			{
				throw new DistributedCacheConnectException("MemcachedClient 连接出错",e);
			}
			pools.put(config, pool);
			return pools.get(config);

		}
	}

	public final void dispose()
	{
	}
}